import os

def read_scores(file_path):
    """读取文件并提取有效分数"""
    scores = []
    try:
        with open(file_path, 'r', encoding='utf-8') as fin:
            for i, line in enumerate(fin, 1):
                line = line.strip()
                if not line:
                    continue  # 跳过空行
                
                parts = line.split(',')
                if len(parts) < 2:
                    raise ValueError(f"格式错误：第{i}行至少需要两个字段")
                
                try:
                    score = int(parts[-1])
                    scores.append(score)
                except ValueError:
                    raise ValueError(f"分数格式错误：第{i}行 '{parts[-1]}' 不是有效整数")
    
    except FileNotFoundError:
        raise FileNotFoundError(f"找不到文件: {file_path}")
    except Exception as e:
        raise RuntimeError(f"读取文件时发生意外错误: {e}")
    
    if not scores:
        raise ValueError("文件中没有找到有效分数")
    
    return scores

def calculate_statistics(scores):
    """计算分数的统计信息"""
    if not scores:
        raise ValueError("无法计算空列表的统计数据")
    
    return max(scores), min(scores), round(sum(scores) / len(scores), 2)

def main():
    """主程序入口"""
    try:
        # 构建文件路径
        file_path = os.path.join(os.getcwd(), "01-exercise/01-20/student_grade_input.txt")
        
        # 读取分数
        scores = read_scores(file_path)
        print(f"成功读取 {len(scores)} 个有效分数")
        
        # 计算统计数据
        max_score, min_score, avg_score = calculate_statistics(scores)
        
        # 输出结果（带千位分隔符）
        print(f"最高分: {max_score:,}")
        print(f"最低分: {min_score:,}")
        print(f"平均分: {avg_score:,}")
    
    except FileNotFoundError as e:
        print(f"错误: {e}")
        print("请确保文件存在于当前工作目录中")
    except ValueError as e:
        print(f"数据错误: {e}")
    except RuntimeError as e:
        print(f"运行时错误: {e}")
    except Exception as e:
        print(f"发生未知错误: {e}")

if __name__ == "__main__":
    main()